package com.niiwoo.civet.trade.service.local.contract;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dao.entity.*;
import com.niiwoo.civet.trade.dao.mapper.FadadaContractTemplateFileMapperExt;
import com.niiwoo.civet.trade.enums.FadadaContractTemplateEnum;
import com.niiwoo.civet.user.dto.response.UserAuthorizationInfoResponseDTO;
import com.niiwoo.civet.user.service.UserAuthorizationInfoDubboService;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO;
import com.niiwoo.tripod.fadada.dto.request.GenerateContractRequestDTO.DynamicTable;
import com.niiwoo.tripod.fadada.dto.response.FadadaResponseDTO;
import com.niiwoo.tripod.fadada.enums.SignClientRoleEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 债权转让服务风险提示书
 * Created by HuangMin on 2018/7/12.
 */
@Service
public class CreditorTransferRiskPrompt extends AbstractFadadaContract {

    private static final Logger logger = LoggerFactory.getLogger(CreditorTransferRiskPrompt.class);

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private FadadaContractTemplateFileMapperExt contractTemplateFileMapperExt;

    @Reference(version = "1.0.0")
    private UserAuthorizationInfoDubboService userAuthorizationInfoDubboService;

    @Override
    public ProjectContract contractHandler(FadadaContractTemplateFile contractTemplate, String bizContractNo,
                                           Project project, String userId) throws Exception {
        return null;
    }

    public ProjectContract contractHandler(FadadaContractTemplateEnum.TemplateTypeEnum templateType,
                                           ProjectInvestOrder projectInvestOrder, CreditorSaleDetail creditorSaleDetail) throws Exception {
        logger.info("债权转让服务风险提示书处理开始... creditorSaleDetailId:{}", creditorSaleDetail.getId());

        String contractId = snowflakeIdWorker.nextId() + "";
        FadadaContractTemplateFile contractTemplateFile = contractTemplateFileMapperExt.queryFadadaContractTemplateFileByTemplateType(templateType.getType());
        if (contractTemplateFile == null) {
            // 借款合同模板不存在
            throw new BizException("TRD_700007", templateType + " templateType not exists.");
        }

        this.generateContract(contractTemplateFile, contractId, projectInvestOrder, creditorSaleDetail);

        ProjectContract result = this.signContract(contractTemplateFile, contractId, projectInvestOrder, creditorSaleDetail);

        this.contractFilling(contractId);
        logger.info("债权转让服务风险提示书处理结束... creditorSaleDetailId:{}", creditorSaleDetail.getId());
        return result;
    }

    private void generateContract(FadadaContractTemplateFile contractTemplate, String contractId,
                                  ProjectInvestOrder projectInvestOrder, CreditorSaleDetail creditorSaleDetail) throws Exception {
        logger.info("债权转让服务风险提示书生成开始... creditorSaleDetailId:{}", creditorSaleDetail.getId());

        GenerateContractRequestDTO dto = new GenerateContractRequestDTO();

        dto.setContractId(contractId);
        dto.setDocTitle(contractTemplate.getTemplateName());
        dto.setTemplateId(contractTemplate.getTemplateId());

        Map<String, String> parameterMap = new HashMap<String, String>();

        List<List<String>> invSignatureNamesList = new ArrayList<>();
        String signDate = DateFormatUtils.format(new Date(), "yyyy年MM月dd日");

        // 出让人签章
        String transferSignatureNamesText = "                                                                                                            出让人（签章）:"
                + creditorSaleDetail.getRealName() + "\n"
                + "                                                                                                            " + signDate;
        List<String> transferSignatureNamesCells = new ArrayList<>();
        transferSignatureNamesCells.add(transferSignatureNamesText);
        invSignatureNamesList.add(transferSignatureNamesCells);

        // 受让人签章
        String assigneeSignatureNamesText = "                                                                                                            受让人（签章）："
                + projectInvestOrder.getInvestorName() + "\n"
                + "                                                                                                            " + signDate;
        List<String> assigneeSignatureNamesCells = new ArrayList<>();
        assigneeSignatureNamesCells.add(assigneeSignatureNamesText);
        invSignatureNamesList.add(assigneeSignatureNamesCells);

        // 投资人姓名列表
        // 表格header
        List<String> headers = new ArrayList<>();
        headers.add("");

        DynamicTable signNameTable = new DynamicTable();
        signNameTable.setInsertWay(1);
        signNameTable.setKeyword("自行享有其投资收益并承担全部损失。");
        signNameTable.setCellHeight(60f);
        signNameTable.setHeaders(headers);
        // 签名时需要增加高度并居中显示
        signNameTable.setCellVerticalAlignment(5);
        signNameTable.setDatas(invSignatureNamesList);
        signNameTable.setBorderFlag(false);
        List<DynamicTable> tables = new ArrayList<DynamicTable>();
        tables.add(signNameTable);

        dto.setDynamicTables(tables);
        dto.setParameterMap(parameterMap);

        generateContract(dto);
        logger.info("债权转让服务风险提示书生成结束... creditorSaleDetailId:{}", creditorSaleDetail.getId());
    }

    private ProjectContract signContract(FadadaContractTemplateFile contractTemplate, String contractId,
                                         ProjectInvestOrder projectInvestOrder, CreditorSaleDetail creditorSaleDetail) throws Exception {
        String METHOD_NAME = "法大大合同自动签署-债权转让服务风险提示书 creditorSaleDetailId:" + creditorSaleDetail.getId();
        logger.info(METHOD_NAME);

        // 授权信息(CA证书编号)
        UserAuthorizationInfoResponseDTO transferUserAuthorizationInfo = userAuthorizationInfoDubboService
                .getUserAuthorizationInfo(creditorSaleDetail.getUserId());
        UserAuthorizationInfoResponseDTO assigneeUserAuthorizationInfo = userAuthorizationInfoDubboService
                .getUserAuthorizationInfo(projectInvestOrder.getUserId());

        String transactionId = null;
        FadadaResponseDTO fadadaResponse = null;
        String docTitle = "债权转让服务风险提示书_" + contractId;

        // 出让人签署
        transactionId = snowflakeIdWorker.nextId() + "";
        String transferCaCertId = transferUserAuthorizationInfo.getFadadaCacertId();
        String transferSignKeyword = "出让人（签章）:" + creditorSaleDetail.getRealName();
        fadadaResponse = extSignAuto(transactionId, contractId, transferCaCertId,
                SignClientRoleEnum.BORROWER.getValue(), docTitle, transferSignKeyword);
        logger.info("法大大合同自动签署-债权转让服务风险提示书 出让人签署结束... creditorSaleDetailId:{}", creditorSaleDetail.getId());

        // 受让人签署
        transactionId = snowflakeIdWorker.nextId() + "";
        String assigneeCaCertId = assigneeUserAuthorizationInfo.getFadadaCacertId();
        String assigneeSignKeyword = "受让人（签章）：" + projectInvestOrder.getInvestorName();
        fadadaResponse = extSignAuto(transactionId, contractId, assigneeCaCertId,
                SignClientRoleEnum.BORROWER.getValue(), docTitle, assigneeSignKeyword);
        logger.info("法大大合同自动签署-债权转让服务风险提示书 出让人签署结束... creditorSaleDetailId:{}", creditorSaleDetail.getId());


        return this.buildContractUpdateRecord(contractTemplate.getTemplateId(), contractId, transactionId,
                fadadaResponse.getViewUrl(), fadadaResponse.getDownloadUrl());
    }

}
